package org.shop.controller.app;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.net.ftp.FTPClient;
import org.shop.util.CommonUtil;
import org.shop.util.DateUtils;
import org.shop.util.FtpUtil2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import sun.misc.BASE64Decoder;

@Controller
public class UploadImgController {
	/**
     * 上传图片
     * @param req
     * @return
     */
    @RequestMapping("app/uplondImg")
    @ResponseBody
    public Map<String, Object> uploadUsedImg(HttpServletRequest req){
        Map<String, Object> map=new HashMap<String, Object>();
        String photoStr="";
        String mainPhotoStr="";
        FTPClient ftpClient =null;
        try{
            //创建一个通用的多部分解析器
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(req.getSession().getServletContext());
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)req;
            //判断 request 是否有文件上传,即多部分请求
            if(multipartResolver.isMultipart(req)){
                //取得request中的所有文件名
                Iterator<String> iter = multiRequest.getFileNames();
                //创建ftp链接
                String ftp_photoDirectory="shop/image/" + DateUtils.toYmdX(new Date());
                ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
                while(iter.hasNext()){
                    String name=iter.next();
                    if(name.equals("goodsMainPhoto")){
                        //取得上传文件
                        List<MultipartFile> fileList = multiRequest.getFiles(name);
                        if(fileList!=null){
                            for(MultipartFile file:fileList){
                                if(file != null){
                                    //取得当前上传文件的文件名称
                                    String myFileName = file.getOriginalFilename();
                                    myFileName=FtpUtil2.generateFileName(myFileName);
                                    //如果名称不为"",说明该文件存在，否则说明该文件不存在
                                    if(myFileName.trim() !=""){
                                        myFileName=FtpUtil2.generateFileName(myFileName);
                                        InputStream is = file.getInputStream();
                                        FtpUtil2.upload(myFileName, is, ftpClient);
                                        mainPhotoStr+=ftp_photoDirectory+"/"+myFileName;
                                    }
                                }
                            }
                        }
                    }else{
                        //取得上传文件
                        List<MultipartFile> fileList = multiRequest.getFiles(name);
                        if(fileList!=null){
                            for(MultipartFile file:fileList){
                                if(file != null){
                                    //取得当前上传文件的文件名称
                                    String myFileName = file.getOriginalFilename();
                                    myFileName=FtpUtil2.generateFileName(myFileName);
                                    //如果名称不为"",说明该文件存在，否则说明该文件不存在
                                    if(myFileName.trim() !=""){
                                        myFileName=FtpUtil2.generateFileName(myFileName)+"jpg";
                                        InputStream is = file.getInputStream();
                                        FtpUtil2.upload(myFileName, is, ftpClient);
                                        if("".equals(photoStr)){
                                            photoStr+=ftp_photoDirectory+"/"+myFileName;
                                        }else{
                                            photoStr+=","+ftp_photoDirectory+"/"+myFileName;;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                map.put("photoStr", photoStr);
                map.put("state", 1);
                map.put("msg", "上传成功");
            }
        }catch(Exception e){
            e.printStackTrace();
            map.put("state", 0);
            map.put("msg", "上传失败");
        }finally {
            try {
                if(ftpClient!=null){
                    FtpUtil2.closeConnection(ftpClient);
                }
            } catch (Exception e) {
                ftpClient=null;
            }
        }
        return map;
    }
    //base64字符串转化成图片  
    public static boolean GenerateImage(String imgStr)  
    {   //对字节数组字符串进行Base64解码并生成图片  
        if (imgStr == null) //图像数据为空  
            return false;  
        BASE64Decoder decoder = new BASE64Decoder();  
        try   
        {  
            //Base64解码  
            byte[] b = decoder.decodeBuffer(imgStr);  
            for(int i=0;i<b.length;++i)  
            {  
                if(b[i]<0)  
                {//调整异常数据  
                    b[i]+=256;  
                }  
            }  
            //生成jpeg图片  
            String imgFilePath = "D:\\tupian\\new.jpg";//新生成的图片  
            OutputStream out = new FileOutputStream(imgFilePath);      
            out.write(b);  
            out.flush();  
            out.close();  
            return true;  
        }   
        catch (Exception e)   
        {  
            return false;  
        }  
    }  
}
